import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import download from '@/utils/download';
import { connect } from 'dva';
import { exportQAHistories } from '@/services/download';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Card, Row, Col, Form, Input, Button, message, Icon, Checkbox, Table, Tag, Select, Modal, Radio, Spin, Upload, Tooltip } from "antd";
import styles from "./index.less";
import x from '@/assets/medicalKnowledge/ABC.png'
import axios from 'axios';
import emptys from '@/assets/icons/emptys.png'

const Search = Input.Search;
const FormItem = Form.Item;
class BusinessDictionary extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      thesaurusList: [],
      pageSize: 9999999,
      page: '',
      showModel: false,
      showModelA: false,
      searchValue: null,
      total: 0,
      fileList: [],
      pdx: null,
      uploading: false,
    };
    this.columns = [
      {
        title: '',
        width: 'calc(10vw)',
        dataIndex: ''
      },
      {
        title: '业务词',
        width: 'calc(70vw)',
        dataIndex: 'name'
      },
      {
        title: '操作',
        width: 'calc(20vw)',
        render: (text, item) => (
          <div className={styles.buttongl} onClick={(text) => { this.handleDeletes(item) }}>
            <span>
              <Icon size="small" type="delete" style={{ marginRight: 5 }} />
            </span>
            <span>
              <FormattedMessage id="app.wordTroughManage.delete" />
            </span>
          </div>
        ),
      },
    ]
  }

  // eslint-disable-next-line react/sort-comp
  fetch = (search = '', page = 1, limit = 99999999) => {
    this.setState({ login: true })
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'businessDictionary/fetch',
        payload: { search, robotId: currentUser.robotId, page, limit },
        callback: res => {
          let temp = res.list
          let list = []
          temp.map((item, index) => {
            let obj = {}
            obj.name = item
            obj.key = index
            list.push(obj)
          })
          console.log('数据', list);
          this.setState({
            thesaurusList: list,
            login: false,
            total: res.total,
            pdx: null
          })
        },
      });
    });
  }

  componentDidMount(val) {
    this.fetch(val)
  }

  answerDetail = () => {
    if (this.state.total === 0) {
      message.error('空列表无法导出！')
    } else {
      const { dispatch, currentUser } = this.props;
      const { searchValue } = this.state
      const data = { search: searchValue }
      dispatch({
        type: 'businessDictionary/fetchf',
        payload: { search: searchValue },
        callback: (res) => {
          let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
          download.byBlob(res.fileBlob, filename)
        }
      });
    }
  }

  impTemp = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'businessDictionary/fetche',
      payload: {},
      callback: (res) => {
        let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
        download.byBlob(res.fileBlob, filename)
      }
    });
  }

  handleDeletes = (e) => {
    console.log(e)
    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'businessDictionary/fetchc',
            payload: { token: currentUser.token, robotId: currentUser.robotId, termName: e.name },
            callback: res => {
              console.log('删除', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`)
                this.fetch(this.state.searchValue)
              }
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel')
      }
    })
  }

  enumeration = () => {
    this.setState({ showModel: true })
  }

  leadWay = () => {
    this.setState({ showModelA: true, fileList: [] })
  }


  handleUpFile = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    if (fileList[0].size > 2000000) { // 2000000
      message.error('上传文件超出2M')
      this.setState({ fileList:[] });
    }else{
      this.setState({ fileList});
    }
  };

  uploadFile = (data) => {
    console.log(data)
    const robotId = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).robotId;
    const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
    axios.post('/cloud/new/basic/lexicon/import', data, {
      method: 'post',
      processData: false,
      headers: { "Content-Type": "application/json", "token": token,'robotId':robotId }
    }).then((res) => {
      this.setState({
        uploading: false
      }, () => {
        if (res.data.code) {
          return message.error(res.data.msg)
        } else {
          this.setState({
            showModelA:false,
            visible: false,
            fileList: [],
            page:1
          }, () => {
            this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
            if (res.data.msg) {
              message.success(res.data.msg);
            } else {
              message.success('导入成功');

            }
          });

        }
      })
    }).catch((error) => {
      message.error('导入失败请稍等再试')
    });
  };


  businessWayA = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      console.log(file)
      formData.append('file', file.originFileObj);
    });
    this.setState({
      uploading: true
    });
    this.uploadFile(formData);
  }

  handleCancel = () => {
    this.setState({ showModelA: false, uploading: false, fileList: [] })
  }

  showRev = (a, b) => {
    //  console.log(a,b)
    this.setState({ pdx: b })
  }

  showRevS = (a, b) => {
    // console.log(a,b)
    this.setState({ pdx: null })
  }



  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 5
      },
      wrapperCol: {
        xs: 24,
        sm: 19
      }
    }
    const { uploading, fileList } = this.state;
    const props = {
      // name: 'file',
      // headers: headData,
      // action: '/cloud/new/basic/lexicon/import',
      // accept: '.xlsx',
      // onChange: this.handleChangeByUpload,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx',
      fileList,
      onChange: this.handleUpFile,
    }
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10,color: '#4B5475', fontWeight: 600 }} xs={24}>
                <div className={styles.title}>
                  <span>业务词库{`(${this.state.total})`}</span>
                  <span style={{ marginLeft: 2,paddingTop:2 }}>
                  <Tooltip
                    placement="top"
                    title="即客户公司专有的一些专业性业务名词，如“花呗”对于支付宝来说就是专业性业务名词。"
                    arrowPointAtCenter
                  >
                    <Icon type="info-circle" />
                  </Tooltip>
                </span>
                </div>
              </Col>
            </Row>
            <Card
              bordered={false}

            >
              <div>
                <div className={styles.fromColumn}>
                  <span className='buttonYs'><Button onClick={this.enumeration} icon="plus"><FormattedMessage id="app.customDictionary.add" defaultMessage="add" /></Button></span>
                  <span className='buttonYs'><Button onClick={this.leadWay} icon="arrow-down">导入</Button></span>
                  <span className='buttonYs'><Button onClick={this.answerDetail} icon="arrow-right">导出</Button></span>
                  <span className={styles.right}>
                    <Search
                      placeholder="请输入搜索内容"
                      onSearch={value => {
                        console.log(value)
                        this.setState({ searchValue: value, page: 1 }, () => {
                          this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
                        })
                      }}
                      style={{ width: 323 }}
                    />
                  </span>
                </div>

                <Spin spinning={this.state.login}>
                  <div className={styles.Tag}>
                    <div style={{ paddingTop: 5 }} className={styles.tagS}>
                      {this.state.total?null: <div className={styles.empty}><img src={emptys} /></div>}
                      {
                        this.state.thesaurusList.map((item, index) => {
                          let color = index % 2 == 1 ? { backgroundColor: '#e8eff6' } : { backgroundColor: '#e8eff6' };
                          let padding = this.state.pdx === index ? { padding: '7px 3px 7px 23px', backgroundColor: 'rgb(232, 239, 216)' } : { padding: '7px 23px', backgroundColor: '#e8eff6' }
                          return (
                            <Suspense> <span onMouseOut={() => { this.showRevS(item, index) }} onMouseOver={() => { this.showRev(item, index) }} style={padding} key={index} className={styles.tag}>{item.name}{this.state.pdx === index ? <img onClick={() => { this.handleDeletes(item) }} className={styles.imgyd} src={x} /> : <img style={{ display: 'none' }} className={styles.imgyd} src={x} />}</span></Suspense>
                          )
                        })
                      }
                    </div>
                  </div>
                </Spin>

                <Modal
                  className='modelZdy'
                  title={<FormattedMessage id="app.businessDictionary.add-word" />}
                  visible={this.state.showModel}
                  okText={<FormattedMessage id="app.customDictionary.save" />}
                  cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
                  onCancel={() => {
                    this.props.form.setFields({ "businessName": "" })
                    this.setState({ showModel: false })
                  }}
                  onOk={this.businessWay}// 确定方法开出去
                >
                  <Form layout="horizontal">
                    <FormItem label='业务词名称' onSubmit={this.coreWordOne} {...FormItemLayont}>
                      {getFieldDecorator('businessName', {
                        initialValue: '',
                        rules: [{ required: true, message: '用户词名称不能为空' }]
                      })(
                        <Input onPressEnter={this.businessWays} />
                      )}
                    </FormItem>
                  </Form>
                </Modal>

                <Modal
                  className='modelZdy'
                  width={550}
                  title={<FormattedMessage id="app.businessDictionary.puload-word" />}
                  visible={this.state.showModelA}
                  footer={[
                    <Button key="back" onClick={this.handleCancel}>
                      取消
                    </Button>,
                    <Button key="submit" type="primary" loading={uploading} disabled={fileList.length === 0} onClick={this.businessWayA}>
                      {uploading ? '导入中' : '开始导入'}
                    </Button>,
                  ]}
                  onCancel={() => {
                    this.setState({ showModelA: false, uploading: false })
                  }}
                >
                  <Form layout="horizontal">
                    <FormItem label='选择文件' onSubmit={this.coreWordOne} {...FormItemLayont}>
                      <Upload {...props} fileList={this.state.fileList}>
                        <Button>
                          <Icon type="upload" /> 选择文件
                        </Button>
                      </Upload>
                    </FormItem>
                    <FormItem label='上传规则' onSubmit={this.coreWordOne} {...FormItemLayont}>
                      <div className={styles.frame}>
                        <div><span>• 请按照模板中的示例格式进行编辑上传：</span> <span onClick={this.impTemp} className={styles.template}>下载xlsx模版</span></div>
                        <div><span>• 上传文件格式需要为“.xlsx”类型的Excel文件</span></div>
                        <div><span>• 导入的业务词数据将覆盖现有数据，请谨慎操作</span></div>
                      </div>
                    </FormItem>
                  </Form>
                </Modal>
              </div>
            </Card>
          </div>
        </PageHeaderWrapper>
      </Suspense >
    );
  }

  onChange = (e) => {
    this.setState({ page: e }, () => {
      this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
    })
    console.log(e)
  }

  onShowSizeChange = (a, b) => {
    console.log(a, b)
    this.setState({ pageSize: b, page: a }, () => {
      this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
    })
  }

  businessWays = (e) => {
    console.log(e.target.value)
    let sj = e.target.value
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法
      if (!err) {
        console.log(userInfo)
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'businessDictionary/fetchb',
            payload: { token: currentUser.token, robotId: currentUser.robotId, termName: sj },
            callback: res => {
              console.log('保存', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`)
                // this.setState({
                //   showModel: false,
                // })
                this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
                this.props.form.setFields({ "businessName": "" })
              }
            },
          });
        });

      }
    })
  }

  businessWay = () => {
    let userInfo = this.props.form.getFieldsValue();// 获取数据
    this.props.form.validateFields((err, values) => {// 校验方法
      if (!err) {
        console.log(userInfo)
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'businessDictionary/fetchb',
            payload: { token: currentUser.token, robotId: currentUser.robotId, termName: userInfo.businessName },
            callback: res => {
              console.log('保存', res);
              if (res.code === 0) {
                message['success'](`${res.msg}`)
                // this.setState({
                //   showModel: false,
                // })
                this.fetch(this.state.searchValue, this.state.page, this.state.pageSize)
                this.props.form.setFields({ "businessName": "" })
              }
            },
          });
        });

      }
    })
  }


}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(BusinessDictionary));
